<?php
class ModelCustomerCustomer extends Model {
	public function addCustomer($data) {
        if (8 == $data['shop_type']) {//终端类型为“正规标准连锁”时，强制修改客户分组，看到另一套价格体系。
            $data['customer_group_id'] = '2';
        }
		$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET user_id = '" . (int)$data['sales_id'] . "',recommended_code = '".$data['recommended_code']."', customer_group_id = '" . (int)$data['customer_group_id'] . "', fullname = '" . $this->db->escape($data['fullname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "', custom_field = '" . $this->db->escape(isset($data['custom_field']) ? json_encode($data['custom_field']) : '') . "', newsletter = '" . (int)$data['newsletter'] . "', salt = '" . $this->db->escape($salt = token(9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "', status = '" . (int)$data['status'] . "', approved = '" . (int)$data['approved'] . "', safe = '" . (int)$data['safe'] . "', date_added = NOW()");

		$customer_id = $this->db->getLastId();

		//Liqn 添加公司名称
		$this->db->query("UPDATE " . DB_PREFIX . "customer SET company_name = '" . $this->db->escape($data['company_name']) . "', need_review = '" . (int)$data['need_review'] . "', is_magfin = '" . (int)$data['is_magfin'] . "', shop_type = '" . (int)$data['shop_type'] . "', logcenter_id = '" . (int)$data['logcenter_id'] . "' WHERE customer_id = '" . (int)$customer_id . "'");

		if (isset($data['address'])) {
			foreach ($data['address'] as $address) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "address SET need_review = '".$address['need_review']."', customer_id = '" . (int)$customer_id . "', fullname = '" . $this->db->escape($address['fullname']) . "', address = '" . $this->db->escape($address['address']) . "', postcode = '" . $this->db->escape($address['postcode']) . "', country_id = '" . (int)$address['country_id'] . "', zone_id = '" . (int)$address['zone_id'] . "', custom_field = '" . $this->db->escape(isset($address['custom_field']) ? json_encode($address['custom_field']) : '') . "'");

				//Liqn 添加city_id
				$address_id = $this->db->getLastId();
				$this->db->query("UPDATE " . DB_PREFIX . "address SET city_id = '" . (int)$address['city_id'] . "', shipping_telephone = '" . $this->db->escape($address['shipping_telephone']) . "' WHERE address_id = '" . (int)$address_id . "'");

				if (isset($address['default'])) {
					// $address_id = $this->db->getLastId();

					$this->db->query("UPDATE " . DB_PREFIX . "customer SET address_id = '" . (int)$address_id . "' WHERE customer_id = '" . (int)$customer_id . "'");
				}
			}
		}

		return $customer_id;

	}

	public function editCustomer($customer_id, $data) {
		if (!isset($data['custom_field'])) {
			$data['custom_field'] = array();
		}
        if (8 == $data['shop_type']) {//终端类型为“正规标准连锁”时，强制修改客户分组，看到另一套价格体系。
            $data['customer_group_id'] = '2';
        }

		$this->db->query("UPDATE " . DB_PREFIX . "customer SET user_id = '" . (int)$data['sales_id'] . "', customer_group_id = '" . (int)$data['customer_group_id'] . "', is_buy = '" . (int)$data['is_buy'] . "',is_all = '" . (int)$data['is_all'] . "',fullname = '" . $this->db->escape($data['fullname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "', custom_field = '" . $this->db->escape(isset($data['custom_field']) ? json_encode($data['custom_field']) : '') . "', newsletter = '" . (int)$data['newsletter'] . "', status = '" . (int)$data['status'] . "', approved = '" . (int)$data['approved'] . "', recommended_code = '". $data['recommended_code'] ."', is_shelf_customer = '". $data['is_shelf_customer'] ."', safe = '" . (int)$data['safe'] . "' WHERE customer_id = '" . (int)$customer_id . "'");
		$sql = "SELECT shop.shop_id, shop.customer_id, shop.shop_name, shop.discount_message, shop.shop_describe, shop.`level`, shop.shelf_num, shop.address, shop.country_id, shop.country, shop.zone_id, shop.zone, shop.city_id, shop.city, shop.lng, shop.lat, shop.`status`, shop.date_added, shop.telephone, shop.qrcode_id, shop.money FROM `shop`";
		$this->db->query($sql);
		$shopinfo = $query->row;
		if (empty($shopinfo)) {
			
		}

		//Liqn 添加公司名称
		$this->db->query("UPDATE " . DB_PREFIX . "customer SET company_name = '" . $this->db->escape($data['company_name']) . "', need_review = '" . (int)$data['need_review'] . "', is_magfin = '" . (int)$data['is_magfin'] . "', shop_type = '" . (int)$data['shop_type'] . "', logcenter_id = '" . (int)$data['logcenter_id'] . "' WHERE customer_id = '" . (int)$customer_id . "'");

		if ($data['password']) {
			$this->db->query("UPDATE " . DB_PREFIX . "customer SET salt = '" . $this->db->escape($salt = token(9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "' WHERE customer_id = '" . (int)$customer_id . "'");
		}

		$this->db->query("DELETE FROM " . DB_PREFIX . "address WHERE customer_id = '" . (int)$customer_id . "'");

		if (isset($data['address'])) {
			foreach ($data['address'] as $address) {
				if (!isset($address['custom_field'])) {
					$address['custom_field'] = array();
				}

				$this->db->query("INSERT INTO " . DB_PREFIX . "address SET need_review = '".$address['need_review']."', address_id = '" . (int)$address['address_id'] . "', customer_id = '" . (int)$customer_id . "', fullname = '" . $this->db->escape($address['fullname']) . "', address = '" . $this->db->escape($address['address']) . "', postcode = '" . $this->db->escape($address['postcode']) . "', country_id = '" . (int)$address['country_id'] . "', zone_id = '" . (int)$address['zone_id'] . "', custom_field = '" . $this->db->escape(isset($address['custom_field']) ? json_encode($address['custom_field']) : '') . "'");

				//Liqn 添加city_id
				$address_id = $this->db->getLastId();
				$this->db->query("UPDATE " . DB_PREFIX . "address SET city_id = '" . (int)$address['city_id'] . "', shipping_telephone = '" . $this->db->escape($address['shipping_telephone']) . "', company = '" . $this->db->escape($address['company']) . "' WHERE address_id = '" . (int)$address_id . "'");

				if (isset($address['default'])) {
					// $address_id = $this->db->getLastId();

					$this->db->query("UPDATE " . DB_PREFIX . "customer SET address_id = '" . (int)$address_id . "' WHERE customer_id = '" . (int)$customer_id . "'");
				}
			}
		}
	}

	public function editToken($customer_id, $token) {
		$this->db->query("UPDATE " . DB_PREFIX . "customer SET token = '" . $this->db->escape($token) . "' WHERE customer_id = '" . (int)$customer_id . "'");
	}

	public function deleteCustomer($customer_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$customer_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "customer_reward WHERE customer_id = '" . (int)$customer_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "customer_transaction WHERE customer_id = '" . (int)$customer_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "customer_ip WHERE customer_id = '" . (int)$customer_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "address WHERE customer_id = '" . (int)$customer_id . "'");
	}

	public function getCustomer($customer_id) {
		$query = $this->db->query("SELECT DISTINCT customer.*,user.fullname as user_name FROM " . DB_PREFIX . "customer  left join " . DB_PREFIX . "user ON customer.user_id = user.user_id WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row;
	}

	public function getCustomerByMobile($customer_mobile){
		$where['telephone'] = array('like',"%".$customer_mobile."%");
		$customer_data = M('customer')
		->where($where)
		->field('customer_id,telephone')
		->select();
		return $customer_data;
	}

	public function getCustomerImages($customer_id) {
		$query = M('customer_images ci')
		->join('upload u on u.code=ci.code')
		->field('u.code as code, u.filename')
		->order('type DESC')
		->where('ci.customer_id="' . $customer_id . '"')
		->select();

		return $query;
	}

	public function getCustomerByEmail($email) {
		$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "customer WHERE LCASE(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		return $query->row;
	}

	public function getCustomers($data = array()) {
		$data = $this->trim_all_arr($data);
		//$sql = "SELECT *, c.fullname, cgd.name AS customer_group, (SELECT ci.code FROM customer_images ci WHERE ci.customer_id=c.customer_id AND type=2) AS license_image_code FROM " . DB_PREFIX . "customer c LEFT JOIN " . DB_PREFIX . "customer_group_description cgd ON (c.customer_group_id = cgd.customer_group_id) WHERE cgd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
        //customer表被长时间锁死，性能优化
        $sql = "
        SELECT
            c.*, cgd.`name` AS customer_group, ci.`code` AS license_image_code
        FROM
            ".DB_PREFIX."customer AS c
            LEFT JOIN `".DB_PREFIX."customer_group_description` AS cgd ON (c.`customer_group_id`=cgd.`customer_group_id` AND `language_id`='".(int)$this->config->get('config_language_id')."')
            LEFT JOIN `".DB_PREFIX."customer_images` AS ci ON (c.`customer_id`=ci.`customer_id` AND `type`='2')
        ";
//echo $sql;
        $implode = array();

		if (!empty($data['filter_name'])) {
			$implode[] = "c.fullname LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
		}

		if (!empty($data['filter_recommended_code'])) {
			$implode[] = "c.recommended_code LIKE '%" . $this->db->escape($data['filter_recommended_code']) . "%' AND c.recommended_code !='' AND c.recommended_code is not null  group by c.recommended_code ";
		}

		if (!empty($data['filter_company_name'])) {
			$implode[] = "c.company_name LIKE '%" . $this->db->escape($data['filter_company_name']) . "%'";
		}

		if (!empty($data['filter_email'])) {
			$implode[] = "c.email LIKE '%" . $this->db->escape($data['filter_email']) . "%'";
		}

		if (!empty($data['filter_telephone'])) {
			$implode[] = "c.telephone LIKE '%" . $this->db->escape($data['filter_telephone']) . "%'";
		}

		if (isset($data['filter_newsletter']) && !is_null($data['filter_newsletter'])) {
			$implode[] = "c.newsletter = '" . (int)$data['filter_newsletter'] . "'";
		}

		if (!empty($data['filter_customer_group_id'])) {
			$implode[] = "c.customer_group_id = '" . (int)$data['filter_customer_group_id'] . "'";
		}

		if (!empty($data['filter_ip'])) {
			$implode[] = "c.customer_id IN (SELECT customer_id FROM " . DB_PREFIX . "customer_ip WHERE ip = '" . $this->db->escape($data['filter_ip']) . "')";
		}

		if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
			$implode[] = "c.status = '" . (int)$data['filter_status'] . "'";
		}

		if (isset($data['filter_logcenter_id']) && !is_null($data['filter_logcenter_id'])) {
			$implode[] = "c.logcenter_id = '" . (int)$data['filter_logcenter_id'] . "'";
		}

		if (isset($data['filter_approved']) && !is_null($data['filter_approved'])) {
			$implode[] = "c.approved = '" . (int)$data['filter_approved'] . "'";
		}

		if (isset($data['filter_need_review']) && !is_null($data['filter_need_review'])) {
			$implode[] = "c.need_review = '" . (int)$data['filter_need_review'] . "'";
		}
		if (isset($data['filter_is_shelf_customer']) && !is_null($data['filter_is_shelf_customer'])) {
			$implode[] = "c.is_shelf_customer = '" . (int)$data['filter_is_shelf_customer'] . "'";
		}

		if (isset($data['filter_is_magfin']) && !is_null($data['filter_is_magfin'])) {
			$implode[] = "c.is_magfin = '" . (int)$data['filter_is_magfin'] . "'";
		}

		if (!empty($data['filter_date_start'])) {
			$implode[] = "DATE(c.date_added) >= DATE('" . $this->db->escape($data['filter_date_start']) . "')";
		}

		if (!empty($data['filter_date_end'])) {
			$implode[] = "DATE(c.date_added) <= DATE('" . $this->db->escape($data['filter_date_end']) . "')";
		}

		if (!empty($data['filter_order_sum']) || $data['filter_order_sum'] === '0') {
			$implode[] = "order_sum = '".$data['filter_order_sum']."'";
		}

		if (!empty($data['filter_last_date_start'])) {
			$implode[] = "last_order_date >= '" . $this->db->escape($data['filter_last_date_start']) . " 00:00:00'";
		}

		if (!empty($data['filter_last_date_end'])) {
			$implode[] = "last_order_date <= '" . $this->db->escape($data['filter_last_date_end']) . " 23:59:59'";
		}

        /*
         * 强制筛选分销商名下用户，用于 controller/customer/customer_distributor
         * @author sonicsjh
         */
        if ((int)$data['filter_user_id'] > 0) {
            $implode[] = "c.user_id ='".(int)$data['filter_user_id']."'";
        }

		if ($implode) {
			$sql .= " WHERE " . implode(" AND ", $implode);
		}

		$sort_data = array(
			'c.fullname',
			'c.email',
			'company_name',
			'customer_group',
			'order_sum',
			'last_order_date',
			'c.status',
			'c.logcenter_id',
			'c.need_review',
			'c.is_magfin',
			'c.approved',
			'c.telephone',
			'c.date_added'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY name";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function approve($customer_id) {
		$customer_info = $this->getCustomer($customer_id);

		if ($customer_info) {
			$this->db->query("UPDATE " . DB_PREFIX . "customer SET approved = '1' WHERE customer_id = '" . (int)$customer_id . "'");

			$this->load->language('mail/customer');

			$this->load->model('setting/store');

			$store_info = $this->model_setting_store->getStore($customer_info['store_id']);

			if ($store_info) {
				$store_name = $store_info['name'];
				$store_url = $store_info['url'] . 'index.php?route=account/login';
			} else {
				$store_name = $this->config->get('config_name');
				$store_url = HTTP_CATALOG . 'index.php?route=account/login';
			}

			$message  = sprintf($this->language->get('text_approve_welcome'), html_entity_decode($store_name, ENT_QUOTES, 'UTF-8')) . "\n\n";
			$message .= $this->language->get('text_approve_login') . "\n";
			$message .= $store_url . "\n\n";
			$message .= $this->language->get('text_approve_services') . "\n\n";
			$message .= $this->language->get('text_approve_thanks') . "\n";
			$message .= html_entity_decode($store_name, ENT_QUOTES, 'UTF-8');

			$mail = new Mail();
			$mail->protocol = $this->config->get('config_mail_protocol');
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
			$mail->smtp_username = $this->config->get('config_mail_smtp_username');
			$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
			$mail->smtp_port = $this->config->get('config_mail_smtp_port');
			$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

			$mail->setTo($customer_info['email']);
			$mail->setFrom($this->config->get('config_email'));
			$mail->setSender(html_entity_decode($store_name, ENT_QUOTES, 'UTF-8'));
			$mail->setSubject(sprintf($this->language->get('text_approve_subject'), html_entity_decode($store_name, ENT_QUOTES, 'UTF-8')));
			$mail->setText($message);
			$mail->send();
		}
	}

	public function getAddress($address_id) {
		$address_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$address_id . "'");

		if ($address_query->num_rows) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$address_query->row['country_id'] . "'");

			if ($country_query->num_rows) {
				$country = $country_query->row['name'];
				$iso_code_2 = $country_query->row['iso_code_2'];
				$iso_code_3 = $country_query->row['iso_code_3'];
				$address_format = $country_query->row['address_format'];
			} else {
				$country = '';
				$iso_code_2 = '';
				$iso_code_3 = '';
				$address_format = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$address_query->row['zone_id'] . "'");

			if ($zone_query->num_rows) {
				$zone = $zone_query->row['name'];
				$zone_code = $zone_query->row['code'];
			} else {
				$zone = '';
				$zone_code = '';
			}

			$city_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "city` WHERE city_id = '" . (int)$address_query->row['city_id'] . "'");

			if ($city_query->num_rows) {
				$city = $city_query->row['name'];
			} else {
				$city = '';
			}

			return array(
				'address_id'     => $address_query->row['address_id'],
				'customer_id'    => $address_query->row['customer_id'],
				'fullname'       => $address_query->row['fullname'],
				'shipping_telephone'       => $address_query->row['shipping_telephone'],
				'company'        => $address_query->row['company'],
				'address'        => $address_query->row['address'],
				'postcode'       => $address_query->row['postcode'],
				'zone_id'        => $address_query->row['zone_id'],
				'zone'           => $zone,
				'zone_code'      => $zone_code,
				'country_id'     => $address_query->row['country_id'],
				'country'        => $country,
				'iso_code_2'     => $iso_code_2,
				'iso_code_3'     => $iso_code_3,
				'address_format' => $address_format,
				'city_id'     	 => $address_query->row['city_id'],
				'city'           => $city,
				'need_review'	 => $address_query->row['need_review'],
				'custom_field'   => json_decode($address_query->row['custom_field'], true)
			);
		}
	}

	public function getAddresses($customer_id) {
		$address_data = array();

		$query = $this->db->query("SELECT address_id FROM " . DB_PREFIX . "address WHERE customer_id = '" . (int)$customer_id . "'");

		foreach ($query->rows as $result) {
			$address_info = $this->getAddress($result['address_id']);

			if ($address_info) {
				$address_data[$result['address_id']] = $address_info;
			}
		}

		return $address_data;
	}

	public function getTotalCustomers($data = array()) {
		$data = $this->trim_all_arr($data);
		$sql = "SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer";

		$implode = array();

		if (!empty($data['filter_name'])) {
			$implode[] = "fullname LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
		}

		if (!empty($data['filter_email'])) {
			$implode[] = "email LIKE '" . $this->db->escape($data['filter_email']) . "%'";
		}

		if (!empty($data['filter_telephone'])) {
			$implode[] = "telephone LIKE '%" . $this->db->escape($data['filter_telephone']) . "%'";
		}

		if (!empty($data['filter_company_name'])) {
			$implode[] = "company_name LIKE '%" . $this->db->escape($data['filter_company_name']) . "%'";
		}

		if (isset($data['filter_newsletter']) && !is_null($data['filter_newsletter'])) {
			$implode[] = "newsletter = '" . (int)$data['filter_newsletter'] . "'";
		}

		if (!empty($data['filter_customer_group_id'])) {
			$implode[] = "customer_group_id = '" . (int)$data['filter_customer_group_id'] . "'";
		}

		if (!empty($data['filter_ip'])) {
			$implode[] = "customer_id IN (SELECT customer_id FROM " . DB_PREFIX . "customer_ip WHERE ip = '" . $this->db->escape($data['filter_ip']) . "')";
		}

		if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
			$implode[] = "status = '" . (int)$data['filter_status'] . "'";
		}

		if (isset($data['filter_logcenter_id']) && !is_null($data['filter_logcenter_id'])) {
			$implode[] = "logcenter_id = '" . (int)$data['filter_logcenter_id'] . "'";
		}

		if (isset($data['filter_approved']) && !is_null($data['filter_approved'])) {
			$implode[] = "approved = '" . (int)$data['filter_approved'] . "'";
		}

		if (isset($data['filter_need_review']) && !is_null($data['filter_need_review'])) {
			$implode[] = "need_review = '" . (int)$data['filter_need_review'] . "'";
		}

		if (isset($data['filter_is_magfin']) && !is_null($data['filter_is_magfin'])) {
			$implode[] = "is_magfin = '" . (int)$data['filter_is_magfin'] . "'";
		}

		if (!empty($data['filter_date_start'])) {
			$implode[] = "DATE(date_added) >= DATE('" . $this->db->escape($data['filter_date_start']) . "')";
		}

		if (!empty($data['filter_date_end'])) {
			$implode[] = "DATE(date_added) <= DATE('" . $this->db->escape($data['filter_date_end']) . "')";
		}

		if (!empty($data['filter_order_sum']) || $data['filter_order_sum'] === 0) {
			$implode[] = "order_sum = '". (int)$data['filter_order_sum'] ."'";
		}

		if (!empty($data['filter_last_date_start'])) {
			$implode[] = "last_order_date >= '" . $this->db->escape($data['filter_last_date_start']) . " 00:00:00'";
		}

		if (!empty($data['filter_last_date_end'])) {
			$implode[] = "last_order_date <= '" . $this->db->escape($data['filter_last_date_end']) . " 23:59:59'";
		}

        /*
         * 强制筛选分销商名下用户，用于 controller/customer/customer_distributor
         * @author sonicsjh
         */
        if ((int)$data['filter_user_id'] > 0) {
            $implode[] = "user_id ='".(int)$data['filter_user_id']."'";
        }

		if ($implode) {
			$sql .= " WHERE " . implode(" AND ", $implode);
		}

		$query = $this->db->query($sql);

		return $query->row['total'];
	}

	public function getTotalCustomersAwaitingApproval() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer WHERE status = '0' OR approved = '0'");

		return $query->row['total'];
	}

	public function getTotalAddressesByCustomerId($customer_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "address WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}

	public function getTotalAddressesByCountryId($country_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "address WHERE country_id = '" . (int)$country_id . "'");

		return $query->row['total'];
	}

	public function getTotalAddressesByZoneId($zone_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "address WHERE zone_id = '" . (int)$zone_id . "'");

		return $query->row['total'];
	}

	public function getTotalCustomersByCustomerGroupId($customer_group_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer WHERE customer_group_id = '" . (int)$customer_group_id . "'");

		return $query->row['total'];
	}

	public function addHistory($customer_id, $comment) {
		$this->db->query("INSERT INTO " . DB_PREFIX . "customer_history SET customer_id = '" . (int)$customer_id . "', comment = '" . $this->db->escape(strip_tags($comment)) . "', date_added = NOW()");
	}

	public function getHistories($customer_id, $start = 0, $limit = 10) {
		if ($start < 0) {
			$start = 0;
		}

		if ($limit < 1) {
			$limit = 10;
		}

		$query = $this->db->query("SELECT comment, date_added FROM " . DB_PREFIX . "customer_history WHERE customer_id = '" . (int)$customer_id . "' ORDER BY date_added DESC LIMIT " . (int)$start . "," . (int)$limit);

		return $query->rows;
	}

	public function getTotalHistories($customer_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer_history WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}

	public function addTransaction($customer_id, $description = '', $amount = '', $order_id = 0) {
		$customer_info = $this->getCustomer($customer_id);

		if ($customer_info) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "customer_transaction SET customer_id = '" . (int)$customer_id . "', order_id = '" . (int)$order_id . "', description = '" . $this->db->escape($description) . "', amount = '" . (float)$amount . "', date_added = NOW()");

			$this->load->language('mail/customer');

			$this->load->model('setting/store');

			$store_info = $this->model_setting_store->getStore($customer_info['store_id']);

			if ($store_info) {
				$store_name = $store_info['name'];
			} else {
				$store_name = $this->config->get('config_name');
			}

			$message  = sprintf($this->language->get('text_transaction_received'), $this->currency->format($amount, $this->config->get('config_currency'))) . "\n\n";
			$message .= sprintf($this->language->get('text_transaction_total'), $this->currency->format($this->getTransactionTotal($customer_id)));

			$mail = new Mail();
			$mail->protocol = $this->config->get('config_mail_protocol');
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
			$mail->smtp_username = $this->config->get('config_mail_smtp_username');
			$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
			$mail->smtp_port = $this->config->get('config_mail_smtp_port');
			$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

			$mail->setTo($customer_info['email']);
			$mail->setFrom($this->config->get('config_email'));
			$mail->setSender(html_entity_decode($store_name, ENT_QUOTES, 'UTF-8'));
			$mail->setSubject(sprintf($this->language->get('text_transaction_subject'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8')));
			$mail->setText($message);
			$mail->send();
		}
	}

	public function deleteTransaction($order_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "customer_transaction WHERE order_id = '" . (int)$order_id . "'");
	}

	public function getTransactions($customer_id, $start = 0, $limit = 10) {
		if ($start < 0) {
			$start = 0;
		}

		if ($limit < 1) {
			$limit = 10;
		}

		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer_transaction WHERE customer_id = '" . (int)$customer_id . "' ORDER BY date_added DESC LIMIT " . (int)$start . "," . (int)$limit);

		return $query->rows;
	}

	public function getTotalTransactions($customer_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total  FROM " . DB_PREFIX . "customer_transaction WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}

	public function getTransactionTotal($customer_id) {
		$query = $this->db->query("SELECT SUM(amount) AS total FROM " . DB_PREFIX . "customer_transaction WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}

	public function getTotalTransactionsByOrderId($order_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer_transaction WHERE order_id = '" . (int)$order_id . "'");

		return $query->row['total'];
	}

	public function addReward($customer_id, $description = '', $points = '', $order_id = 0) {
		$customer_info = $this->getCustomer($customer_id);

		if ($customer_info) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "customer_reward SET customer_id = '" . (int)$customer_id . "', order_id = '" . (int)$order_id . "', points = '" . (int)$points . "', description = '" . $this->db->escape($description) . "', date_added = NOW()");

			$this->load->language('mail/customer');

			$this->load->model('setting/store');

			$store_info = $this->model_setting_store->getStore($customer_info['store_id']);

			if ($store_info) {
				$store_name = $store_info['name'];
			} else {
				$store_name = $this->config->get('config_name');
			}

			$message  = sprintf($this->language->get('text_reward_received'), $points) . "\n\n";
			$message .= sprintf($this->language->get('text_reward_total'), $this->getRewardTotal($customer_id));

			$mail = new Mail();
			$mail->protocol = $this->config->get('config_mail_protocol');
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
			$mail->smtp_username = $this->config->get('config_mail_smtp_username');
			$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
			$mail->smtp_port = $this->config->get('config_mail_smtp_port');
			$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

			$mail->setTo($customer_info['email']);
			$mail->setFrom($this->config->get('config_email'));
			$mail->setSender(html_entity_decode($store_name, ENT_QUOTES, 'UTF-8'));
			$mail->setSubject(sprintf($this->language->get('text_reward_subject'), html_entity_decode($store_name, ENT_QUOTES, 'UTF-8')));
			$mail->setText($message);
			$mail->send();
		}
	}

	public function deleteReward($order_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "customer_reward WHERE order_id = '" . (int)$order_id . "' AND points > 0");
	}

	public function getRewards($customer_id, $start = 0, $limit = 10) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer_reward WHERE customer_id = '" . (int)$customer_id . "' ORDER BY date_added DESC LIMIT " . (int)$start . "," . (int)$limit);

		return $query->rows;
	}

	public function getTotalRewards($customer_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer_reward WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}

	public function getRewardTotal($customer_id) {
		$query = $this->db->query("SELECT SUM(points) AS total FROM " . DB_PREFIX . "customer_reward WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}

	public function getTotalCustomerRewardsByOrderId($order_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer_reward WHERE order_id = '" . (int)$order_id . "' AND points > 0");

		return $query->row['total'];
	}

	public function getIps($customer_id, $start = 0, $limit = 10) {
		if ($start < 0) {
			$start = 0;
		}
		if ($limit < 1) {
			$limit = 10;
		}

		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer_ip WHERE customer_id = '" . (int)$customer_id . "' ORDER BY date_added DESC LIMIT " . (int)$start . "," . (int)$limit);
		return $query->rows;
	}

	public function getTotalIps($customer_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer_ip WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->row['total'];
	}

	public function getTotalCustomersByIp($ip) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer_ip WHERE ip = '" . $this->db->escape($ip) . "'");

		return $query->row['total'];
	}

	public function getTotalLoginAttempts($email) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "customer_login` WHERE `email` = '" . $this->db->escape($email) . "'");

		return $query->row;
	}

	public function deleteLoginAttempts($email) {
		$this->db->query("DELETE FROM `" . DB_PREFIX . "customer_login` WHERE `email` = '" . $this->db->escape($email) . "'");
	}

	public function getMreward($customer_id){
		if(!($customer_id)){
			$customer_id = 0;
		}
		$where['customer_id'] = $customer_id;
		$cr = M('customer_reward');
		$Mreward = $cr
		->where($where)
		->where("date_format(date_added,'%Y-%m') = date_format(now(),'%Y-%m')")
		->field("SUM(points) as m")
		->select();
		$Mreward = $Mreward['0']['m'];
		$Areward = $cr
		->where($where)
		->field("SUM(points) as a")
		->select();
		$Areward = $Areward['0']['a'];
		$data  = array(
			'Areward' => $Areward,
			'Mreward' => $Mreward,
			);
		return $data;
	}

	public function getExportCustomer($data=array()) {
		$data = $this->trim_all_arr($data);
		$map = array();

		if (!empty($data['filter_name'])) {
			$map['c.fullname'] = array("like","%".$data['filter_name']."%");
		}
		if (!empty($data['filter_customer_group_id'])) {
			$map['c.customer_group_id'] = (int)$data['filter_customer_group_id'];
		}
		if (!empty($data['filter_approved'])) {
			$map['c.filter_approved'] = (int)$data['filter_approved'];
		}
		/*if (!empty($data['filter_date_added'])) {
			$added_start = $data['filter_date_added'];
			$added_end = $data['filter_date_added']." 23:59:59";
			$map['c.date_added'] = array('between',array($added_start,$added_end));
		}*/

		if ((!empty($data['filter_date_start']))&&(!empty($data['filter_date_end']))) {
			$filter_date_end = $data['filter_date_end']." 23:59:59";
			$map['c.date_added'] = array('between',array($data['filter_date_start'],$filter_date_end));
		}
		else {

			if (!empty($data['filter_date_start'])) {
			$map['c.date_added'] = array('egt',$data['filter_date_start']);
			}

			if (!empty($data['filter_date_end'])) {
				$filter_date_end2 = $data['filter_date_end']." 23:59:59";
				$map['c.date_added'] = array('elt',$filter_date_end2);
			}

		}

		if (!empty($data['filter_email'])) {
			$map['c.email'] = array("like","%".$data['filter_email']."%");
		}
		if (!empty($data['filter_status'])) {
			$map['c.status'] = (int)$data['filter_status'];
		}
		if (!empty($data['filter_telephone'])) {
			$map['c.telephone'] = array("like","%".$data['filter_telephone']."%");
		}
		if (!empty($data['filter_logcenter_id'])) {
			$map['c.logcenter_id'] = (int)$data['filter_logcenter_id'];
		}
		if (!empty($data['filter_company_name'])) {
			$map['c.company_name'] = array("like","%".$data['filter_company_name']."%");
		}

		$query = M('customer c')
        ->join('LEFT join address a on c.address_id=a.address_id')
		->where($map)
		->order('date_added desc')
        ->field('c.*,a.fullname as a_fullname,a.company,a.address,a.city as a_city,a.postcode,a.country_id,a.zone_id,a.custom_field as a_custom_field,a.shipping_telephone,a.city_id,a.need_review as a_need_review')//@author sonicsjh 修正c表和a表的字段冲突导致的导出信息异常
		->select();
		//echo  M('customer c')->getLastSql();
		return $query;
	}

	public function updateRecommendCodeByTelephone($data){
		$model = M('customer');
		$data['user_id'] = $data['recommend_user_id'];
		$map['telephone'] = $data['telephone'];
		$model->data($data)->where($map)->save();
	}

	public function editShopType($data){
		$model = M('customer');
		foreach($data as $key=>$value){
			$arr['shop_type'] = $value['type'];
			$map['telephone'] = $value['telephone'];
			$model->data($arr)->where($map)->save();
		}
	}

	//过滤空格之类不可见的字符串
	public function trim_all_arr($data){
		$newdata = $data;
		foreach($newdata as $key=>$val){
			if($newdata[$key]!=null)
				$newdata[$key] = trim($val);
		}
		return $newdata;
	}

	//判断是否发送新注册优惠券
	public function getSendNew($customer_id){

		$status = M('customer')->where('customer_id='.$customer_id)->getField('send_new');
		return $status;

	}

	//查找autocomplete超市名称
	public function getAutoCompleteCustomers($data){

		$customer = M('customer')->where($data)->limit('10')->select();
		return $customer;

	}

	//查找用户充值单据
	public function getRechargeOrder($customer_id){

		//会员给我的充值记录
		$account = M('customer')->where('customer_id='.$customer_id)->getField('telephone');
		$c_where['account'] = $account;
		$c_where['runner_type'] = 1;
		$c_where['balance_type'] = 1;

		$c_recharge = M('balance_recharge')
			->alias('br')
			->join('customer c on br.runner_id = c.customer_id','left')
			->join('balance_status bs on br.status = bs.id','left')
			->join('runner_type rt on br.runner_type = rt.id')
			->where($c_where)->order('date_added desc')->field('c.fullname as runner,bs.name as status_name,rt.name as rtype,br.*')->select();

		//业务员给我的充值记录
		$account = M('customer')->where('customer_id='.$customer_id)->getField('telephone');
		$u_where['account'] = $account;
		$u_where['runner_type'] = 2;
		$u_where['balance_type'] = 1;

		$u_recharge = M('balance_recharge')
			->alias('br')
			->join('user u on br.runner_id = u.user_id','left')
			->join('balance_status bs on br.status = bs.id','left')
			->join('runner_type rt on br.runner_type = rt.id')
			->where($u_where)->order('date_added desc')->field('u.username as runner,bs.name as status_name,rt.name as rtype,br.*')->select();

		$recharge = array_merge($c_recharge,$u_recharge);

		/*按照时间排序*/
		foreach($recharge as $key=>$v){
			$recharge[$key]['date_added'] = date('Y-m-d H:i:s',strtotime($v['date_added']));
		}
		$datetime = array();
		foreach ($recharge as $v) {
			$datetime[] = $v['date_added'];
		}
		array_multisort($datetime,SORT_DESC,$recharge);
		/*按照时间排序*/

		return $recharge;

	}

	//查找用户定金单据
	public function getDepositOrder($customer_id){

		//会员给我的充值记录
		$account = M('customer')->where('customer_id='.$customer_id)->getField('telephone');
		$c_where['account'] = $account;
		$c_where['runner_type'] = 1;
		$c_where['balance_type'] = 2;

		$c_deposit = M('balance_recharge')
			->alias('br')
			->join('customer c on br.runner_id = c.customer_id','left')
			->join('balance_status bs on br.status = bs.id','left')
			->join('runner_type rt on br.runner_type = rt.id')
			->join('balance_type bt on br.balance_type = bt.id')
			->where($c_where)->order('date_added desc')->field('c.fullname as runner,bs.name as status_name,rt.name as rtype,bt.name as btype,br.*')->select();

		//业务员给我的充值记录
		$account = M('customer')->where('customer_id='.$customer_id)->getField('telephone');
		$u_where['account'] = $account;
		$u_where['runner_type'] = 2;
		$u_where['balance_type'] = 2;

		$u_deposit = M('balance_recharge')
			->alias('br')
			->join('user u on br.runner_id = u.user_id','left')
			->join('balance_status bs on br.status = bs.id','left')
			->join('runner_type rt on br.runner_type = rt.id')
			->join('balance_type bt on br.balance_type = bt.id')
			->where($u_where)->order('date_added desc')->field('u.username as runner,bs.name as status_name,rt.name as rtype,bt.name as btype,br.*')->select();

		$deposit = array_merge($c_deposit,$u_deposit);

		/*按照时间排序*/
		foreach($deposit as $key=>$v){
			$deposit[$key]['date_added'] = date('Y-m-d H:i:s',strtotime($v['date_added']));
		}
		$datetime = array();
		foreach ($deposit as $v) {
			$datetime[] = $v['date_added'];
		}
		array_multisort($datetime,SORT_DESC,$deposit);
		/*按照时间排序*/

		return $deposit;

	}

	//查找用户余额支付订单单据
	public function getTradeOrder($customer_id){

		$where['`order`.customer_id'] = $customer_id;
		$where['`order`.payment_code'] = 'balance';
		$order = M('order')
			->join('order_status os on `order`.order_status_id = os.order_status_id','left')
			->where($where)->order('`order`.date_added desc')->field('os.name as status_name,`order`.*')->select();

		return $order;

	}

	//查找用户的当前余额
	public function getBalance($customer_id){

		 $old_balance = M('customer')->where('customer_id='.$customer_id)->getField('balance');

		 return $old_balance;

	}

	//手动添加用户充值
	public function addRechargeOrder($customer_id,$data){

		if($data['type'] == 0){
			$data['money'] = -$data['money'];
		}

		$account = M('customer')->where('customer_id='.$customer_id)->getField('telephone');

		$temp = array (

			'runner_id' => $_SESSION['default']['user_id'],
			'runner_type' => 2,
			'account' => $account,
			'money' => $data['money'],
			'payment_method' => '手工添加',
			'payment_code' => 'system',
			'balance_type' => 1,
			'status' => 3,
			'memo' => $data['memo'],
			'date_added' => date('Y-m-d H:i:s')

		);

		M('balance_recharge')->data($temp)->add();
		M('customer')->where('customer_id='.$customer_id)->setInc('balance',$data['money']);

		$balance = M('customer')->where('customer_id='.$customer_id)->getField('balance');

		return $balance;

	}

	//手动添加定金
	public function addDepositOrder($customer_id,$data){

		$account = M('customer')->where('customer_id='.$customer_id)->getField('telephone');

		$temp = array (

			'runner_id' => $_SESSION['default']['user_id'],
			'runner_type' => 2,
			'account' => $account,
			'money' => $data['money'],
			'payment_method' => '手工添加',
			'payment_code' => 'system',
			'balance_type' => 2,
			'status' => 3,
			'memo' => $data['memo'],
			'date_added' => date('Y-m-d H:i:s')

		);

		M('balance_recharge')->data($temp)->add();

	}

	public function getcustomer_id(){
		$sql=$this->db->query("SELECT customer_id FROM `".DB_PREFIX."customer` where status=1");
		return $sql->rows;
	}
	//获取用户月份统计表格
	public function getExporstatistics($ids){
								   //日期
						        $start= '2016-05';
						        $startarr = explode('-', $start);
						        $end  = date("Y-m");
						        $endarr = explode('-', $end);
						        for ($i=(int)$startarr[1]; $i <=12 ; $i++) {
						        	if ($i>=10) {
						   				$dateArr[] = $startarr[0].$i;
						   			}else{
						   				$dateArr[] = $startarr[0].'0'.$i;
						   			}
						        }
						        if ($endarr[0]-$startarr[0]>=2) {
						        	for ($j=$startarr[0]+1; $j <(int)$endarr[0]; $j++) {
							        	for ($i=1; $i <=12 ; $i++) {
								        	if ($i>=10) {
								   				$dateArr[] = $j.$i;
								   			}else{
								   				$dateArr[] = $j.'0'.$i;
								   			}
								        }
							        }

						        }


						        for ($i=1; $i <=(int)$endarr[1] ; $i++) {
						        	if ($i>=10) {
						   				$dateArr[] = $endarr[0].$i;
						   			}else{
						   				$dateArr[] = $endarr[0].'0'.$i;
						   			}
						        }

						        //查询所有用户订单信息
						        foreach ($ids as $k => $v) {
						        	 $sql = "SELECT extract(YEAR_MONTH FROM o.date_added) AS 'yearMonth',o.fullname,o.shipping_company, sum(o.total) AS 'total', COUNT(o.order_id) AS 'num',u.fullname,c.fullname AS customer_name,o.payment_country,o.payment_zone,o.shipping_address,c.date_added,c.recommended_code  FROM `order` AS o left join `customer` AS c on c.customer_id=o.customer_id left join `user` AS u on u.user_id=c.user_id WHERE o.order_status_id <> 16 AND o.order_status_id <> 0 AND o.order_status_id <> 13 AND o.order_status_id <> 11 AND  o.customer_id =".$v."  AND o.date_added>'".$start."-01 00:00:00' GROUP BY extract(YEAR_MONTH FROM o.date_added)";
									        // echo $sql;
									         $query = $this->db->query($sql);
									         $info[]= $query->rows;
						        }

						        $first=array();


						        foreach ($info as $key => $value) {
						        				$sumnum=0;
						        		 		$sumtotal=0;
									        foreach ($value as $k => $v) {
									        		  	$yearMonth = $v['yearMonth'];
												        	$yearArr = str_split($v['yearMonth'],4);
												        	$v['yearMonth'] = $yearArr[0].'-'.$yearArr[1];
												        	$sumnum+=$info[$key][$k]['num'];
							        		 				$sumtotal+=$info[$key][$k]['total'];
												        	$v['first']=$info[$key][0]['yearMonth'];
												        	$v['sumnum']=$sumnum;
												        	$v['sumtotal']=$sumtotal;
												          $infoarr[$key][$yearMonth] = $v;
									        }
						        	}


						         foreach ($dateArr as $key => $value) {
							        	foreach ($infoarr as $k => $v) {
							        			//如果不是它key值给它补全数据
								        		if(!array_key_exists($value, $v)){
										        		$yearArr = str_split($value,4);
										        		$value1 = $yearArr[0].'-'.$yearArr[1];
										        		foreach ($v as $ke => $va) {
																		$infoarr[$k][$value]['yearMonth'] = $value1;
																		$infoarr[$k][$value]['customer_name'] = $infoarr[$k][$ke]['customer_name'];//会员号
																		$infoarr[$k][$value]['payment_country'] = $infoarr[$k][$ke]['payment_country'];//省市
																		$infoarr[$k][$value]['payment_zone'] = $infoarr[$k][$ke]['payment_zone'];//城市
																		$infoarr[$k][$value]['shipping_address'] = $infoarr[$k][$ke]['shipping_address'];//超市地址
																		$infoarr[$k][$value]['fullname'] = $infoarr[$k][$ke]['fullname'];//客户经理
																		$infoarr[$k][$value]['recommended_code'] = $infoarr[$k][$ke]['recommended_code'];//推荐码
																		$infoarr[$k][$value]['date_added'] = $infoarr[$k][$ke]['date_added'];//注册时间
																		$infoarr[$k][$value]['first'] = $infoarr[$k][$ke]['first'];//首单时间
																		$infoarr[$k][$value]['shipping_company'] = $infoarr[$k][$ke]['shipping_company'] ;//超市名称
																		$infoarr[$k][$value]['sumnum'] = $infoarr[$k][$ke]['sumnum'];//单数汇总
																		$infoarr[$k][$value]['sumtotal'] = $infoarr[$k][$ke]['sumtotal'];//金额汇总
												        		$infoarr[$k][$value]['total'] = "";
												        		$infoarr[$k][$value]['num'] = "";
										        		}
								        		}

							        		}
						        	}

						        $bigData = array();
						         foreach($infoarr as $key => $val){
								         	foreach($val as $k => $v){
								         		$bigData[$key]['会员号'] = $v['customer_name'];
								         		$bigData[$key]['会员所在城市'] = $v['payment_zone'];
								         		$bigData[$key]['会员超市地址'] = $v['shipping_address'];
								         		$bigData[$key]['会员超市名称'] = $v['shipping_company'];
								         		$bigData[$key]['会员所在省市'] = $v['payment_country'];
								         		$bigData[$key]['首次注册时间'] = str_split($v['date_added'],10)[0];
								         		$bigData[$key]['首单时间'] = $v['first'];
								         		$bigData[$key]['客户经理'] = $v['fullname'];
								         		$bigData[$key]['推荐码'] = $v['recommended_code'];
								         		$bigData[$key]['订单汇总'] = $v['sumnum'];
								         		$bigData[$key]['订单金额汇总'] = $v['sumtotal'];
								         		$bigData[$key][$k.'金额'] = $v['total'];
								         		$bigData[$key][$k.'单数'] = $v['num'];
								         	}
								            ksort($bigData[$key]);
						         }


						        return $bigData;

	}
}
